package com.example.emptytest;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.example.emptytest.DB.SQLiteHelper;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;

import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity implements View.OnClickListener {

    private TextView mBtn_Login;
    private View progress;
    private View m_Input_layout;
    private float mWidth,mHeight;
    private LinearLayout mName,mPsw;
    private Timer timer;
    private TextView mBtn_forgetpswd;
    private TextView mBtn_register;
    private ImageView mBtn_exit;
    private EditText mInput_num,mInput_pswd;
    private SQLiteHelper helper;
    private Cursor cursor;
    // 登录线程

    private boolean ckLogin = false;
    //定义一个变量，来标识系统秒
    private long exitTime=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); // 隐藏标题栏
        setContentView(R.layout.activity_main);
        helper = new SQLiteHelper(this);
        initView();
    }

    private void initView(){
        mBtn_Login = findViewById(R.id.btn_login);
        progress = findViewById(R.id.layout_progress);
        m_Input_layout = findViewById(R.id.input_layout);
        mName = findViewById(R.id.input_layout_name);
        mPsw = findViewById(R.id.input_layout_psw);
        mBtn_forgetpswd = findViewById(R.id.btn_forgetpswd);
        mBtn_register = findViewById(R.id.btn_register);
        mBtn_exit = findViewById(R.id.btn_exit);
        mInput_num = findViewById(R.id.input_num);
        mInput_pswd = findViewById(R.id.input_pswd);

        mBtn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();// 创建Intent对象
                intent.setAction(Intent.ACTION_MAIN);// 设置Intent动作
                intent.addCategory(Intent.CATEGORY_HOME);// 设置Intent种类
                startActivity(intent);// 将Intent传递给Activity
            }
        });

        mBtn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,ForgetPswd.class);
                startActivity(intent);
            }
        });
        mBtn_forgetpswd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("忘记密码");
                builder.setMessage("本系统绑定账号与教务网相同，登录时请输入教务网账号密码。" +
                        "忘记密码请到教务网操作。");
                builder.setNegativeButton("知道了",new DialogInterface.OnClickListener(){

                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
                builder.create().show();
            }
        });
        mBtn_Login.setOnClickListener((View.OnClickListener) this);


    }

    @Override
    public void onClick(View v) {
        // 计算出控件的高宽
        mWidth = mBtn_Login.getMeasuredWidth();
        mHeight = mBtn_Login.getMeasuredHeight();
        // 隐藏输入框
        mName.setVisibility(View.INVISIBLE);
        mPsw.setVisibility(View.INVISIBLE);

        inputAnimator(m_Input_layout, mWidth, mHeight);

    }

    private void doPostLog(String username, String password) {
        String uriAPI = "";
        try{
            URL url = new URL(uriAPI);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("POST");
            // 数据
            String data = "user_name="+username+"&password="+password;
            // 请求头
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            connection.setRequestProperty("Content-Type",data.length()+"");
            // post 提交
            connection.setDoInput(true);
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(data.getBytes());

            // 回复
            int responseCode = connection.getResponseCode();
            switch (responseCode){
                case 0:
                    Toast toast0 = Toast.makeText(MainActivity.this, "账号不存在", Toast.LENGTH_SHORT);
                    toast0.setGravity(Gravity.CENTER, 0, 0);
                    toast0.show();
                    recovery();
                    break;
                case 1:
                    Toast toast1 = Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT);
                    toast1.setGravity(Gravity.CENTER, 0, 0);
                    toast1.show();
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
                            startActivity(intent);
                            MainActivity.this.finish();
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task,1000);
                    break;
                case 2:
                    Toast toast2 = Toast.makeText(MainActivity.this, "请不要使用脚本", Toast.LENGTH_SHORT);
                    toast2.setGravity(Gravity.CENTER, 0, 0);
                    toast2.show();
                    recovery();
                    break;
                case 3:
                    Toast toast3 = Toast.makeText(MainActivity.this, "密码错误", Toast.LENGTH_SHORT);
                    toast3.setGravity(Gravity.CENTER, 0, 0);
                    toast3.show();
                    recovery();
                    break;
                case 4:
                    Toast toast4 = Toast.makeText(MainActivity.this, "服务器故障，请稍后再试", Toast.LENGTH_SHORT);
                    toast4.setGravity(Gravity.CENTER, 0, 0);
                    toast4.show();
                    recovery();
                    break;
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }

    /* view 控件 w 宽  h 高 */
        private void inputAnimator(final View view, float w, float h){
            AnimatorSet set = new AnimatorSet();

            ValueAnimator animator = ValueAnimator.ofFloat(0, w);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (Float) animation.getAnimatedValue();
                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view
                            .getLayoutParams();
                    params.leftMargin = (int) value;
                    params.rightMargin = (int) value;
                    view.setLayoutParams(params);
                }
            });

            ObjectAnimator animator2 = ObjectAnimator.ofFloat(m_Input_layout,
                    "scaleX", 1f, 0.5f);
            set.setDuration(1000);
            set.setInterpolator(new AccelerateDecelerateInterpolator());
            set.playTogether(animator, animator2);
            set.start();
            set.addListener(new Animator.AnimatorListener() {

                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    /**
                     * 动画结束后，先显示加载的动画，然后再隐藏输入框
                     */
                    progress.setVisibility(View.VISIBLE);
                    progressAnimator(progress);
                    m_Input_layout.setVisibility(View.INVISIBLE);
                    String num = mInput_num.getText().toString();
                    String pswd = mInput_pswd.getText().toString();

                    if((num.compareTo("123") == 0)
                        && (pswd.compareTo("123") == 0)) {
                            Toast toast = Toast.makeText(MainActivity.this, "管理员模式", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                            TimerTask task = new TimerTask() {
                                @Override
                                public void run() {
                                    Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
                                    intent.putExtra("STNum","123");
                                    startActivity(intent);
                                    MainActivity.this.finish();
                                }
                            };
                            Timer timer = new Timer();
                            timer.schedule(task,1000);
                        }
                    else
                    {
                        // 非管理员
                        //doPostLog(num,pswd);
                        String args[] = new String[]{"%" + num + "%"};
                        cursor = helper.query(args);
                        if(cursor.getCount() == 0){
                            Toast toast0 = Toast.makeText(MainActivity.this, "账号未注册或者不存在", Toast.LENGTH_SHORT);
                            toast0.setGravity(Gravity.CENTER, 0, 0);
                            toast0.show();
                            recovery();
                        }
                        else{
                            System.out.println(cursor.getCount());
                            if(cursor.moveToFirst()) {//cursor读取数据
                                if(cursor.getString(cursor.getColumnIndex("STPswd")).compareTo(pswd) == 0){
                                    Toast toast1 = Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT);
                                    toast1.setGravity(Gravity.CENTER, 0, 0);
                                    toast1.show();
                                    TimerTask task = new TimerTask() {
                                        @Override
                                        public void run() {
                                            Intent intent = new Intent(MainActivity.this,WelcomeActivity.class);
                                            intent.putExtra("STNum",cursor.getString(cursor.getColumnIndex("STNum")));
                                            startActivity(intent);
                                            MainActivity.this.finish();
                                        }
                                    };
                                    Timer timer = new Timer();
                                    timer.schedule(task,1000);
                                }
                                else {
                                    Toast toast3 = Toast.makeText(MainActivity.this, "密码错误", Toast.LENGTH_SHORT);
                                    toast3.setGravity(Gravity.CENTER, 0, 0);
                                    toast3.show();
                                    recovery();
                                }
                            }
                            else{
                                Toast toast2 = Toast.makeText(MainActivity.this, "数据库查询出错", Toast.LENGTH_SHORT);
                                toast2.setGravity(Gravity.CENTER, 0, 0);
                                toast2.show();
                                recovery();
                            }
                        }


                    }
                    //recovery();

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }
            });

        }

        /* 出现进度动画 view */
        private void progressAnimator(final View view) {
            PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX",
                    0.5f, 1f);
            PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY",
                    0.5f, 1f);
            ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(view,
                    animator, animator2);
            animator3.setDuration(1000);
            animator3.setInterpolator(new Interpolator());
            animator3.start();

        }


    /* 恢复初始状态 */
    private void recovery() {
        progress.setVisibility(View.GONE);
        m_Input_layout.setVisibility(View.VISIBLE);
        mName.setVisibility(View.VISIBLE);
        mPsw.setVisibility(View.VISIBLE);

        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) m_Input_layout.getLayoutParams();
        params.leftMargin = 0;
        params.rightMargin = 0;
        m_Input_layout.setLayoutParams(params);


        ObjectAnimator animator2 = ObjectAnimator.ofFloat(m_Input_layout, "scaleX", 0.5f,1f );
        animator2.setDuration(500);
        animator2.setInterpolator(new AccelerateDecelerateInterpolator());
        animator2.start();
    }

    // 重写返回
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
            return false;
        }
        return super.onKeyDown(keyCode,event);
    }

    private void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(getApplicationContext(),
                    "再按一次退出程序", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        }
        else{
            finish();
            System.exit(0);
        }
    }



}